package com.hk.service.business;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: dpb
 * @date: 2022/11/29
 */
@Service
@Slf4j
public class LockBusiness {
    private static int count = 10000;

    private static Object object = new Object();

    //可以使用原子类来解决
//    AtomicInteger a = new AtomicInteger(1);
//    AtomicInteger b = new AtomicInteger(1);

    volatile int a = 1;
    volatile int b = 1;


//    public void add() {
//        log.info("add start。。。。。");
////        synchronized (object) {
//            for (int i = 0; i < count; i++) {
//                a.incrementAndGet();
//                b.incrementAndGet();
//            }
////        }
//        log.info("add done。。。。。");
//    }

//    public  void compare() {
//        log.info("compare start.......");
//        for (int i = 0; i < count; i++) {
//            if (a.get() < b.get()) {
//                log.info("a:{}, b:{}, {}", a, b ,a.get() > b.get());
//            }
//        }
//
//        log.info("compare done.......");
//    }

    public synchronized void add() {
        log.info("add start");
        for (int i = 0; i < 10000; i++) {
            a++;
            b++;
        }
        log.info("add done");
    }

    public synchronized void compare() {
        log.info("compare start");
        for (int i = 0; i < 10000; i++) {
            //a始终等于b吗？
            if (a < b) {
                log.info("a:{},b:{},{}", a, b, a > b);
                //最后的a>b应该始终是false吗？
            }
        }
        log.info("compare done");

    }

    public void slow() {
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
        }
    }


}
